import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

const login = () => import('../page/user/login')
const registerMail = () => import('../page/user/registerMail')
const registerUserInfo = () => import('../page/user/registerUserInfo')
const bindingBankCard = () => import('../page/user/bindingBankCard')
const registerSuccess = () => import('../page/user/registerSuccess')
const bookList = () => import('../page/bookPage/bookList')
const bookDetail = () => import('../page/bookPage/bookDetail')
const bookSearch = () => import('../page/bookPage/bookSearch')
const orderList = () => import('../page/bookPage/orderList')
const userInfo = () => import('../page/user/userInfo')
const shoppingCart = () => import('../page/user/shoppingCart')
const orderBook = () => import('../page/bookPage/orderBook')

Vue.use(Router)

const routes = [
    { path: '/login', component: login },
    { path: '/registerMail', component: registerMail },
    { path: '/registerUserInfo', component: registerUserInfo },
    { path: '/bindingBankCard', component: bindingBankCard },
    { path: '/registerSuccess', component: registerSuccess },
    { path: '/bookList', component: bookList, alias: '/'},
    { path: '/bookDetail', component: bookDetail },
    { path: '/bookSearch', component: bookSearch },
    { path: '/userInfo', component: userInfo, meta: { requiresAuth: true }},
    { path: '/orderList', component: orderList, meta: { requiresAuth: true }},
    { path: '/shoppingCart', component: shoppingCart, meta: { requiresAuth: true }},
    { path: '/orderBook', component: orderBook, meta: { requiresAuth: true }},
    { path: '/orderList', component: orderList, meta: { requiresAuth: true }}
];

export const router = new Router({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.getters['user/userId']) {
      if(from.matched.some(record => record.path === '/login')) {
        next({ path: '/' })
      } else {
        next({ path: '/login' })
      }
    } else {
      next()
    }
  } else {
    next()
  }
})
